package com.meizu.asum.richtextsdk.tools;

import com.meizu.asum.richtextsdk.view.RichEditText;
import com.meizu.asum.richtextsdk.vo.SpanVO;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description： 文本分离工具<br>
 * User：Xie JunWen <br>
 * Email：v-xiejunwen@meizu.com <br>
 * CreateTime：2018/1/18  16:21 <br>
 * Remark：无
 */
public class TextSeparationTools {
    private RichEditText richEditText;

    public TextSeparationTools(RichEditText richEditText) {
        this.richEditText = richEditText;
    }

    public ArrayList<SpanVO> sep(String content) {
        ArrayList<SpanVO> spans = new ArrayList<>();

        for (String emoticonName : richEditText.getEmoticonIconTable().getEmoticonIconNames()) {
            int findIndex = content.indexOf(emoticonName);
            while (findIndex != -1) {
                SpanVO spanVO = new SpanVO();
                spanVO.setStartIndex(findIndex);
                spanVO.setEndIndex(findIndex + emoticonName.length());
                spanVO.setContent(emoticonName);
                spanVO.setType(0);
                spans.add(spanVO);

                StringBuffer space = new StringBuffer(emoticonName.length());
                for (int i = 0; i < emoticonName.length(); i++) {
                    space.append("-");
                }

                content = content.substring(0, spanVO.getStartIndex()) + space + content.substring(spanVO.getEndIndex());
                findIndex = content.indexOf(emoticonName);
            }
        }

        Pattern r = Pattern.compile(richEditText.getPicStartWrap() + ".*?" + richEditText.getPicEndWrap());
        Matcher m = r.matcher(content);
        while (m.find()) {
            int startIndex = m.start();
            int endIndex = m.end();
            String pic = m.group();

            SpanVO spanVO = new SpanVO();
            spanVO.setStartIndex(startIndex);
            spanVO.setEndIndex(endIndex);
            spanVO.setContent(pic);
            spanVO.setType(1);
            spans.add(spanVO);
        }

        return spans;
    }
}
